<?php

class ProductOrderTable extends Doctrine_Table
{
	const STATUS_NEW = "new";
	const STATUS_PAID = "paid";
	const STATUS_CANCELED = "canceled";
	const ORDER_START = 210000;
	
	public function checkout( array $products, PublicUser $user, Currency $payInCurrency, $billingData, $shippingData ){
		$order = new ProductOrder();
		
		$order_nr = Doctrine::getTable('ProductOrder')->createQuery()->select('MAX(o.order_number) as lastOrder')->from('ProductOrder o')->execute(array(),Doctrine::HYDRATE_ARRAY);
                $order_nr = $order_nr[0]['lastOrder'];
                
		if($order_nr >= ProductOrderTable::ORDER_START){
		    $order_nr = $order_nr+1;
		}
		else{
                   
		    $order_nr = ProductOrderTable::ORDER_START;
		}
		   
		$order->fromArray(
			array(	'public_user_id' => $user->getId(),
					'order_number' => $order_nr,
					'order_ref_number' => (int)$this->calcReferenceNumber($order_nr)-1,
					'status' => ProductOrderTable::STATUS_NEW,
					'pay_in_currency' => $payInCurrency['abbr']
					 )
		);
		
		$order->save();
		
		
		$billing = new ProductOrderBilling();
		$billing->fromArray(
				array_merge(
					$billingData,
					array('order_id' => $order['id'])
				)
		);
		$billing->save();

		$shipping = new ProductOrderShipping();
		$shipping->fromArray(
				array_merge(
					$shippingData,
					array(
						'order_id' => $order['id'],
						'price_currency' => $payInCurrency['abbr']
						)
				)
		);
		$shipping->save();
		
		foreach($products as $productID => $qty){
			$product = Doctrine::getTable('Product')->find($productID);
			$item = new ProductOrderItem();
			$item->fromArray(
				array(	'order_id' => $order['id'],
						'product_id' => $productID,
						'quanity' => $qty,
						'mass' => $product['mass'],
						'vatrate' => $product['vatrate'],
						'code' => $product['code'],
						'price' => $product['price_actual'],
						'name' => $product['name'],
						'order_shipping_id' => $shipping['id']));
			$item->save();
		}
		
		return $order;
		
	}
	
	static function calcReferenceNumber($nr){
	    
	     $nr = (string)$nr;
	     $kaal = array(7,3,1);
	     $sl = $st = strlen($nr);
	     $total = 0;
	     while($sl > 0 and substr($nr, --$sl, 1) >='0'){
		 $total += substr($nr, ($st-1)-$sl, 1)*$kaal[($sl%3)];
	     }
	     $kontrollnr = ((ceil(($total/10))*10)-$total);
	     return '3'.$nr.$kontrollnr;

	}	
        
        public function directoInvoice($order_id){
            $q = Doctrine_Query::create()
            ->select('po.*, pu.*, poi.*, pos.*, pob.*')
            ->from('ProductOrder po')
            ->innerJoin('po.OrederedItems poi')
            ->innerJoin('po.PublicUser pu')
            ->innerJoin('po.BillingAddress pob')
            ->innerJoin('po.Shippings pos')
            ->whereIn('po.id', $order_id)
            ->setHydrationMode(Doctrine::HYDRATE_ARRAY);

            $res = $q->execute();
            $res = $res[0];
            $billing = $res['BillingAddress'];

            $xmlLine = '';
            $total = 0;
            foreach($res['OrederedItems'] as $item){		
                $xmlLine .= '<line ProductID="'.$item['id'].'" Quantity="'.$item['quanity'].'" UnitPriceWoVAT="'.round($item['price']/1.09).'" ProductName="'.$item['name'].'"></line>';
                $total = $total+$item['price'];

            }

            $xmlStr = '<invoice Number="'.$res['order_number'].'" InvoiceDate="'.$res['created_at'].'" CustomerCode="'.$billing['code'].'" Address1="'.$billing['street'].', '.$billing['zip'].'" Address2="'.$billing['city'].'" CustomerName="'.$billing['receiver'].'" Email="'.$billing['email'].'" Phone="'.$billing['phone'].'" TotalWoVAT="'.round($total/1.09).'" TotalVAT="'.$total.'">';
            $xmlStr .= $xmlLine.'</invoice>';
            $xml = '<?xml version="1.0" encoding="UTF-8"?>
            <xml>
              <invoices>
              ' . $xmlStr . '
              </invoices>
            </xml>';	

            //echo $xml;

            $directoInvoice = SimpleWebService::getWebService(SimpleWebService::DIRECTO_INPUT)->getRequest('invoice',array('xml'=>$xml));
            $directoInvoice->send();
            
            
        }
        


}